import { Button } from 'antd'
import { useState } from 'react'
import { useRequest } from 'alova/client'
import { useEventEmitter, useMount } from 'ahooks'

import { Http } from '../../Utils/Api'
import { refreshStore } from '../../Config/zustand'
import { getInitMenu } from '../../Utils/TableConfig'
import { DevextremeTemplate } from '../../Utils/Devextreme'


// 默认页码配置
const defaultPagig = { pageIndex: 1, pageSize: 1000 }
const pageConfig = { url: 'getRole', page: 'TwoPageRole' }

const RoleList = ({ init, Off }) => {
    const { updateRefresh } = refreshStore()

    const [selectRowkeys, setSelectRowkeys] = useState()
    const { send } = useRequest(({ url, params }) => Http({ url, params }), { immediate: false })

    const [Config, setConfig] = useState()
    const [dataSource, setDataSource] = useState()

    useMount(async () => {
        const { data, page } = await getInitMenu({ url: pageConfig.url, config: pageConfig.page, defaultPagig })
        const { list } = data.data
        page.tableConfig.selectionMode = 'multiple'
        page.tableConfig.selectionShowCheckBoxesMode = 'onClick'
        setConfig(page)
        setDataSource(list)
        setSelectRowkeys(init.roleUuid ? init.roleUuid.split(',') : [])
    })

    const findUniqueStrings = (arr1, arr2) => {
        const set1 = new Set(arr1);
        const arr = arr2.filter(item => !set1.has(item))
        const uuids = dataSource.map(item => item.uuid)
        return arr.filter(item => uuids.includes(item))
    }


    const onSubmit = () => {
        const oldArr = init.roleUuid ? init.roleUuid.split(',') : []
        const params = {
            userUuid: init.uuid,
            addRoleUuid: selectRowkeys,
            deleteRoleUuid: findUniqueStrings(selectRowkeys, oldArr)
        }
        send({ url: 'posRoleUserAddRoleUserNew', params }).then(res => {
            updateRefresh(new Date().getTime())
            Off()
        })
    }

    const DevEvent = useEventEmitter()
    DevEvent.useSubscription(val => {
        const { type, data } = val
        if (type === 'onSelectionChanged') setSelectRowkeys(data)
    })

    return (
        <div className="CommonMenu RoleList">
            <div className='Table'>
                {selectRowkeys && dataSource && Config &&
                    <DevextremeTemplate
                        dataSource={dataSource}
                        config={Config}
                        selectRowkeys={selectRowkeys}
                        DevEvent={DevEvent}
                        ColumnOptions={() => []}
                    />
                }
            </div>
            <div className='Submit'>
                <Button type='primary' size='large' onClick={onSubmit}>保存</Button>
            </div>
        </div>
    );
};

export default RoleList;